<template>
  <div class="chat">
    <div id="chat-content" ref="chatContent">
      <el-card
        class="msg-card"
        :body-style="bodyStyle(message.type)"
        v-for="message in messages"
      >
        <el-avatar :src="message.avatar"></el-avatar>
        <div
          class="msg-blub"
          :style="message.type === 0 ? '' : 'align-items: end;'"
        >
          <el-link type="info">{{ message.username }}</el-link>
          <div v-html="message.content"></div>
        </div>
      </el-card>
    </div>
    <div class="chat-form">
      <x-edit ref="xEditRef" class="edit"></x-edit>
      <el-button class="send-button" type="primary" @click="handleSendMessage"
        >发送</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { useStore } from "vuex";
import { baseURL } from "@/config/axios.config";
import ReconnectingWebSocket from "reconnectingwebsocket";
import { ElMessage } from "element-plus";
import { clearLogged } from "@/utils/stateUtils";

const store = useStore();
const messages = ref([]);
const xEditRef = ref();

const bodyStyle = computed(
  () => (type) =>
    `display:flex;align-items:center;${
      type === 0 ? "" : "flex-direction: row-reverse;"
    }`
);
const socket = new ReconnectingWebSocket(
  baseURL.replace("http", "ws") + "/chat",
  store.getters.loggedUser.token
);
socket.onmessage = ({ data }) => {
  const msg = JSON.parse(data);
  messages.value.push(msg);
};
socket.addEventListener("error", () => {
  ElMessage.error("连接到聊天服务器失败, 请重新登录");
  clearLogged();
  setTimeout(() => (window.location = "/#/login"), 500);
});
const handleSendMessage = () => {
  const content = xEditRef.value.getHtml();
  if (!content) {
    ElMessage.error("请输入要发送的消息!");
    return;
  }
  const { name: username, avatar } = store.getters.loggedUser;
  socket.send(content);
  messages.value.push({
    username,
    avatar,
    type: 1,
    content,
  });
  xEditRef.value.clear();
  scrollButtom();
};
const scrollButtom = () => {
  nextTick(() => {
    const div = document.getElementById("chat-content");
    div.scrollTop = div.scrollHeight;
  });
};
</script>

<style scoped>
.msg-blub {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  margin-right: 10px;
  align-items: start;
}
.chat {
  width: 50%;
}
#chat-content {
  max-height: 500px;
  overflow: auto;
}
.chat-form {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.send-button {
  margin-left: 10px;
  margin-top: 10px;
}
.msg-card {
  margin-top: 10px;
}
.edit {
  width: auto !important;
}
</style>
